package com.seguriapp.services;

import static com.google.common.collect.Lists.newArrayList;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.seguriapp.dao.MenuLinkDao;
import com.seguriapp.dao.UserDao;
import com.seguriapp.entities.MenuLink;
import com.seguriapp.entities.MenuLinkRole;
import com.seguriapp.entities.User;

/**
 * Security Service Implementation
 * 
 * @author Tania Gonzales (taniadgv@gmail.com)
 */
@Service
public class SecurityServiceImpl implements SecurityService {

  @Autowired
  private UserDao userDao;

  @Autowired
  private MenuLinkDao menuLinkDao;

  public void setUserDao(final UserDao userDao) {
    this.userDao = userDao;
  }

  public void setMenuLinkDao(final MenuLinkDao menuLinkDao) {
    this.menuLinkDao = menuLinkDao;
  }

  @Transactional
  public User getUserInitialData(final User userQuery) {
    final User user = userDao.getUserInitialData(userQuery);
    return user;
  }

  @Transactional
  public List<MenuLink> getMenuLinkListByRole(final String roleStr) {
    final MenuLinkRole role = MenuLinkRole.getEnumByString(roleStr);
    if (role != null) {
      return menuLinkDao.getMenuLinkListByRole(role);
    }
    return newArrayList();
  }

  @Transactional
  public long getUsersTotalPages(int pageSize) {
    return userDao.getUsersTotalPages(pageSize);
  }

  @Transactional
  public List<User> listUsersOrderByColumn(final int page, final int pageSize, final boolean ascending, final String columnSort) {
    return userDao.listUsersOrderByColumn(page, pageSize, ascending, columnSort);
  }

  @Transactional
  public String saveUserData(User user) {
    try {
      if (user.getId() != null) {
        final User dbUser = userDao.findById(user.getId());
        if (dbUser != null && !dbUser.getUsername().equals(user.getUsername())) {
          if (!userDao.isValidUserName(user.getUsername())) {
            return "El usuario ya existe, por favor seleccionar otro.";
          } else {
            user = dbUser;
          }
        }
      } else {
        if (!userDao.isValidUserName(user.getUsername())) {
          return "El usuario ya existe, por favor seleccionar otro.";
        }
      }
      userDao.save(user);
    } catch (Exception e) {
      return "Hubo un error al guardar el usuario, por favor intente nuevamente.";
    }
    return null;
  }

  @Transactional
  public List<Long> getUserEntities(final Long userId) {
    return userDao.getUserEntities(userId);
  }

  @Transactional
  public void saveUser(final User user) {
    userDao.save(user);
  }

}
